package com.xinruke.hostels.support.controller;


import com.xinruke.hostels.common.controller.BaseController;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.support.common.Constants;
import com.xinruke.hostels.support.common.FileUtils;
import com.xinruke.hostels.support.common.ImgSuffix;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


@RestController
@RequestMapping("/common")
@Api(tags = "通用工具服务")
public class CommonController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${tmp.upload.path}")
    private String uploadTempPath;

    @Value("${server.web.url}")
    private String appIp;

    @ResponseBody
    @PostMapping(value = "/uploadImg")
    @ApiOperation("上传图片")
    public ResultVO uploadImg(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        logger.info("开始上传图片");
        String fileName = "";
        String imgPath = "";
        //默认上传成功
        String imageUploadFlag = "0";
        InputStream in = null;
        try {
            logger.info("file={}", (file != null ? file.getOriginalFilename() : null));
            if (file != null && file.getInputStream().available() != 0) {
                fileName = file.getName();
                // 单个文件上传
                // 转化上传图片流--file
                CommonsMultipartFile cf = (CommonsMultipartFile) file;
                DiskFileItem fi = (DiskFileItem) cf.getFileItem();
                File f = fi.getStoreLocation();
                in = file.getInputStream();
                //String IMGS_SOURCE_PATH = request.getSession().getServletContext().getRealPath(uploadTempPath);
                String imageSourcePath = uploadTempPath;

//				 FTP/ETCP/{TYPE}/关联ID/XXX.JPG
                String type = Constants.PRIVILAGE_FLAG_PRODUCT;
                if (ImgSuffix.checkImgSuffix(file.getOriginalFilename()) == true) {
                    long fileLen = f.length();
                    if (fileLen > 5L * 1024 * 1024) {
                        logger.error("上传文件超过5M, fileSize={}", fileLen);
                        imageUploadFlag = Constants.IMAGES_STATUS_OVERSIZE;
                        //return Constants.IMAGES_STATUS_OVERSIZE;
                    } else {
                        imgPath = FileUtils.uploadFiles(imageSourcePath, f, in, file.getOriginalFilename(), type, "");
                        if (StringUtils.isBlank(imgPath)) {
                            logger.info("上传图片失败, imgPath={}", imgPath);
                            imageUploadFlag = Constants.IMAGES_STATUS_LLEGAL;
                        } else {
                            imgPath = appIp + imgPath;
                            logger.info("上传图片成功, imgPath={} fileSize={}", imgPath, fileLen);
                        }
                    }
                } else {
                    // 上传文件不合法
                    imageUploadFlag = Constants.IMAGES_STATUS_LLEGAL;
                }

            } else {
                // 上传失败
                logger.info("上传图片失败");
                imageUploadFlag = Constants.IMAGES_STATUS_FILE;
            }
        } catch (IOException e) {
            logger.error("文件流异常：e=", e);
            // 上传文件不合法
            imageUploadFlag = Constants.IMAGES_STATUS_LLEGAL;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map map = new HashMap();
        map.put("url", imgPath);
        map.put("uploadFlag", imageUploadFlag);
        ResultVO<Map> resultVO = ResultVO.success();
        resultVO.setData(map);
        return resultVO;
    }

    @ResponseBody
    @PostMapping(value = "/uploadImgBatch")
    @ApiOperation("批量上传图片")
    public ResultVO uploadImgBatch(@RequestParam(value = "file") MultipartFile[] files, HttpServletRequest request) {
        logger.info("批量开始上传图片");
        Set<String> imgSet = new HashSet<>();
        StringBuffer imgsArray = new StringBuffer();
        String imgPath = "";
        //默认上传成功
        String imageUploadFlag = "0";
        InputStream in = null;
        if (files != null && files.length > 0) {
            logger.info("files num={}", (files != null ? files.length : 0));
            if (files.length > 9) {
                imageUploadFlag = Constants.IMAGES_STATUS_OVERMAXNUM;
            } else {
                for (MultipartFile file : files) {
                    try {
                        String fileName = file.getName();
                        // 单个文件上传
                        // 转化上传图片流--file
                        CommonsMultipartFile cf = (CommonsMultipartFile) file;
                        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
                        File f = fi.getStoreLocation();
                        in = file.getInputStream();
                        String imageSourcePath = uploadTempPath;

                        String type = Constants.PRIVILAGE_FLAG_PRODUCT;
                        if (ImgSuffix.checkImgSuffix(file.getOriginalFilename()) == true) {
                            long fileLen = f.length();
                            if (fileLen > 5L * 1024 * 1024) {
                                logger.error("上传文件超过5M, fileSize={}", fileLen);
                                imageUploadFlag = Constants.IMAGES_STATUS_OVERSIZE;
                                //return Constants.IMAGES_STATUS_OVERSIZE;
                            } else {
                                imgPath = FileUtils.uploadFiles(imageSourcePath, f, in, file.getOriginalFilename(), type, "");
                                if (StringUtils.isBlank(imgPath)) {
                                    logger.info("上传图片失败, imgPath={}", imgPath);
                                    imageUploadFlag = Constants.IMAGES_STATUS_LLEGAL;
                                } else {
                                    imgPath = appIp + imgPath;
                                    imgSet.add(imgPath);
                                    imgsArray.append(imgPath).append(",");
                                    logger.info("上传图片成功, imgPath={} fileSize={}", imgPath, fileLen);
                                }
                            }
                        } else {
                            // 上传文件不合法
                            imageUploadFlag = Constants.IMAGES_STATUS_LLEGAL;
                        }
                    } catch (IOException e) {
                        logger.error("文件流异常：e=", e);
                        // 上传文件不合法
                        imageUploadFlag = Constants.IMAGES_STATUS_LLEGAL;
                    } finally {
                        try {
                            if (in != null) {
                                in.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else {
            imageUploadFlag = Constants.IMAGES_STATUS_FILE;
        }

        Map map = new HashMap();
        map.put("uploadFlag", imageUploadFlag);
        map.put("imgUrlsSet", imgSet);
        map.put("imgUrlsStr", (imgsArray.toString().endsWith(",") ? imgsArray.subSequence(0, imgsArray.length() - 1).toString() : imgsArray.toString()));
        ResultVO<Map> resultVO = ResultVO.success();
        resultVO.setData(map);
        return resultVO;
    }

    private String getPostBody(InputStream is, int contentLen) {
        if (contentLen > 0) {
            int readLen = 0;
            int readLengthThisTime = 0;
            byte[] message = new byte[contentLen];
            try {
                while (readLen != contentLen) {
                    readLengthThisTime = is.read(message, readLen, contentLen - readLen);
                    if (readLengthThisTime == -1) {// Should not happen.
                        break;
                    }
                    readLen += readLengthThisTime;
                }
                return new String(message);
            } catch (IOException e) {
            }
        }
        return "";
    }

    private void response(HttpServletRequest request, HttpServletResponse response, String results, int status) throws IOException {
        String callbackFunName = request.getParameter("callback");
        response.addHeader("Content-Length", String.valueOf(results.length()));
        if (callbackFunName == null || callbackFunName.equalsIgnoreCase("")) {
            response.getWriter().println(results);
        } else {
            response.getWriter().println(callbackFunName + "( " + results + " )");
        }
        response.setStatus(status);
        response.flushBuffer();
    }

}
